# tools/read_file.py
""" 
author：Men Dong Yang
create_time：2025/5/7 14:03:12
description：读取各种文件
"""
import yaml


def read_api_info(api_name, read_body=True):
    # 读取接口信息存入line 字典
    line = read_yaml('config/api.yaml', api_name)
    # 添加一行host
    line['host'] = read_yaml('config/host.yaml', 'host')
    # 读取头
    if 'admin' in line['path']:
        headers = read_yaml('config/headers.yaml')['admin']
    else:
        headers = read_yaml('config/headers.yaml')['client']
    # 读取body
    if line['method'] in ['POST', 'PUT'] and read_body:
        body = read_yaml(f'datafiles/{api_name}.yaml')
    else:
        body = None
    api_info = {
        "line": line,
        "headers": headers,
        "body": body
    }
    return api_info


def read_yaml(filename, key=None):
    """
    读取yaml文件
    :param filename: 文件名
    :param key: 读取文件中指定数据,不输入值就是获取全部
    :return:可能是一个字典或字符串
    """
    # 打开文件并起别名f
    with open(filename, 'rb') as f:
        data = yaml.safe_load(f)
        if key is None:  # 如果key值为空
            return data  # 返回全部数据
        else:  # 如果key值有值
            return data[key]  # 返回指定数据
